#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(&tcpServer, SIGNAL(newConnetion()), this, SLOT(onNewConnection));
    connect(&timer, SIGNAL(timeOut), SLOT(onTimeOut()));
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_createButton_clicked()
{
    port = ui->portEdit->text().toShort();
    if(tcpServer.listen(QHostAddress::Any, port) == true){
        printf("创建服务器成功\n");
        ui->createButton->setEnabled(false);
        ui->portEdit->setEnabled(false);
        timer.start(3000);
    }else{
        printf("创建服务器失败\n");
    }
}
void Widget::onNewConnection(){
    QTcpSocket* tcpClient = tcpServer.nextPendingConnection();
    tcpClientList.append(tcpClient);
    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}
void Widget::onReadyRead(){
    for(int i=0; i<tcpClientList.size(); i++){
        if(tcpClientList[i]->bytesAvailable()){
            QByteArray buf = tcpClientList[i]->readAll();
            ui->listWidget->addItem(buf);
            ui->listWidget->scrollToBottom();
            sendMessage(buf);
        }
    }
}
void Widget::sendMessage(const QByteArray& buf){
    for(int i=0; i<tcpClientList.size(); i++){
        if(tcpClientList[i]->state() == QAbstractSocket::UnconnectedState){
            tcpClientList.removeAt(i);
            i--;
        }
    }
}
